package service;

import dao.OrderDao;
import dao.TableDao;
import dao.TableInfoDao;
import dao.impl.OrderDaoImpl;
import dao.impl.TableDaoImpl;
import dao.impl.TableInfoDaoImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;
import pojo.Order;
import pojo.Table;
import pojo.TableInfo;
import util.Result;
import util.SendCodeUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

public class OrderService {

    private OrderDao orderDao = new OrderDaoImpl();
    private TableDao tableDao = new TableDaoImpl();
    private TableInfoDao tableInfoDao= new TableInfoDaoImpl();


    /**
     * 根据条件查找所有订单
     * @param request
     * @param response
     */
    public void orderList(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            Order order = new Order();
            BeanUtils.populate(order, parameterMap);
            List<Order> orders = orderDao.orderList(order);
            if (orders==null){
                Result.response(1001,"查找失败！", response);
                return;
            }
            Result.response(0 ,"查找成功!", orderDao.countOrderList(order), response, orders);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看订单详细信息
     * @param request
     * @param response
     */
    public void orderInfoPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String tableId = request.getParameter("tableId");
        String orderId = request.getParameter("orderId");
        List<Table> tableList = tableDao.tableList();
        for (Table table : tableList) {
            if (table.getTableId().toString().equals(tableId)){
                TableInfo tableInfo = tableInfoDao.findTableInfoByOrderId(orderId);
                table.setTableInfo(tableInfo);
                request.getSession().setAttribute("table",table);
                request.getRequestDispatcher("/WEB-INF/pages/orderManage/orderInfo.jsp").forward(request, response);
            }
        }
    }
    //@Test
    //public void test() {
    //    String code = SendCodeUtil.sendCode("15183095132");
    //    System.out.println("code = " + code);
    //}
}
